class FriendGroupManager {
    constructor() {
        this.contactList = document.getElementById('contact-list');
        this.detailContainer = document.querySelector('.global-div-column.col-8');
        this.userId = null;
        this.userName = null;
        this.selectedContact = null;

        this.initializeUser();
    }

    async initializeUser() {
        try {
            const userData = await window.clickBtn.getUserDataObject();
            this.userId = userData.userId;
            this.userName = userData.userName;
            
            await this.fetchContacts();
        } catch (error) {
            console.error('获取用户信息失败:', error);
            this.contactList.innerHTML = '<div class="error-message">初始化失败，请刷新页面重试</div>';
        }
    }

    async fetchContacts() {
        try {
            this.contactList.innerHTML = '<div class="loading-indicator">加载中...</div>';

            const response = await fetch(`http://${_HOST_}:${_PORT_}/GetInfo`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId: this.userId
                })
            });

            const data = await response.json();
            
            if (data.code === '0000') {
                this.updateContactList(data.messages);
            } else {
                throw new Error(data.msg || '获取联系人列表失败');
            }
        } catch (error) {
            console.error('获取联系人列表失败:', error);
            this.contactList.innerHTML = '<div class="error-message">获取联系人列表失败，请刷新页面重试</div>';
        }
    }

    updateContactList(messages) {
        this.contactList.innerHTML = '';

        if (messages && messages.length > 0) {
            const listContainer = document.createElement('div');
            listContainer.className = 'contact-list';

            messages.forEach(item => {
                const contactItem = document.createElement('div');
                contactItem.className = 'contact-item';
                contactItem.dataset.id = item.id;
                
                contactItem.innerHTML = `
                    <div class="contact-info">
                        <span class="contact-type">${item.type === 'user' ? '👨' : '👨‍👨‍👦'}</span>
                        <span class="contact-name">${item.name}</span>
                    </div>
                `;

                contactItem.addEventListener('click', () => {
                    const previousSelected = this.contactList.querySelector('.contact-item.active');
                    if (previousSelected) {
                        previousSelected.classList.remove('active');
                    }
                    
                    contactItem.classList.add('active');
                    
                    this.showContactDetail(item);
                });

                listContainer.appendChild(contactItem);
            });

            this.contactList.appendChild(listContainer);
        } else {
            this.contactList.innerHTML = '<div class="empty-list">您目前好友列表为空~</div>';
        }
    }

    showContactDetail(contact) {
        this.detailContainer.innerHTML = `
            <div class="contact-detail">
                <div class="contact-avatar"></div>
                <div class="contact-detail-name">${contact.name}</div>
                <div class="contact-detail-id">ID: ${contact.id}</div>
                <div class="contact-detail-type">${contact.type === 'user' ? '好友' : '群组'}</div>
            </div>
        `;
    }
}

// 初始化管理器
document.addEventListener('DOMContentLoaded', () => {
    const friendGroupManager = new FriendGroupManager();
});
